niu
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 分类树 -->
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <MaterialCategoryTree
          ref="categoryTreeRef"
          v-model="queryParams.categoryIds"
          @node-click="handleQuery"
        />
      </el-col>
      <el-col :lg="20" :xs="24">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item prop="keywords" label="关键字">
              <el-input
                v-model="queryParams.keywords"
                placeholder="关键字"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select v-model="queryParams.type" clearable style="width: 100px">
                <el-option
                  v-for="item in MaterialType"
                  :key="item"
                  :label="Material_LABEL[item]"
                  :value="item"
                />
              </el-select>
            </el-form-item>

            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar">
            <div class="data-table__toolbar--actions">
              <el-button type="primary" plain icon="plus" @click="handleOpenDialog()">
                新增
              </el-button>
              <!-- <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
            删除
          </el-button> -->
            </div>
          </div>

          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="houseList"
            highlight-current-row
            border
            class="data-table__content"
          >
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column label="材料名称" prop="name" width="150" />
            <el-table-column label="材料类型" width="150">
              <template #default="scope">
                {{ Material_LABEL[scope.row.type] }}
              </template>
            </el-table-column>
            <el-table-column label="编码" prop="code" width="150" />
            <el-table-column label="市场价" width="120" align="right" prop="price">
              <template #default="scope">
                {{ `￥${scope.row.price}` }}
              </template>
            </el-table-column>
            <el-table-column label="成本价" width="120" align="right" prop="costPrice">
              <template #default="scope">
                {{ `￥${scope.row.costPrice}` }}
              </template>
            </el-table-column>
            <el-table-column label="规格" prop="spec" width="150" />
            <el-table-column label="单位" prop="unit" width="150" />
            <el-table-column label="描述" align="center" min-width="150" prop="remark" />
            <el-table-column fixed="right" label="操作" width="220">
              <template #default="scope">
                <el-button
                  :disabled="scope.row.systemd"
                  type="primary"
                  size="small"
                  link
                  icon="edit"
                  @click="handleOpenDialog(scope.row.id)"
                >
                  编辑
                </el-button>
                <el-button
                  :disabled="scope.row.systemd"
                  type="danger"
                  size="small"
                  link
                  icon="delete"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="fetchData"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 客户表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="材料名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入材料名称" />
        </el-form-item>
        <el-form-item label="材料分类" prop="categoryId">
          <el-tree-select
            v-model="formData.categoryId"
            placeholder="请选择定额分类"
            :data="categoryOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="材料类型" prop="type">
          <el-select v-model="formData.type" :disabled="!!formData.id" placeholder="请选择">
            <el-option
              v-for="item in MaterialType"
              :key="item"
              :label="Material_LABEL[item]"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="材料编码" prop="code">
          <el-input
            :disabled="!!formData.id"
            v-model="formData.code"
            placeholder="请输入编码，不输入则自动生成"
          />
        </el-form-item>
        <el-form-item label="市场价" prop="price">
          <el-input-number
            v-model="formData.price"
            :precision="2"
            :step="1"
            :min="1"
            style="width: 180px"
          >
            <template #prefix>
              <span>￥</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice">
          <el-input-number
            v-model="formData.costPrice"
            :precision="2"
            :step="1"
            :min="1"
            style="width: 180px"
          >
            <template #prefix>
              <span>￥</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="材料规格" prop="spec">
          <el-input v-model="formData.spec" placeholder="请输入材料规格" />
        </el-form-item>
        <el-form-item label="材料单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入材料单位" />
        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入客户描述" />
        </el-form-item>
        <el-form-item label="图片">
          <MultiUpload
            v-model="formData.files"
            :limit="1"
            :file-types="['image/jpeg', 'image/png']"
            :max-size="5"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import MultiUpload from "@/components/Upload/MultiUpload.vue";
import AttachUtil from "@/utils/attachUtil";
import MaterialCategoryTree from "./MaterialCategoryTree.vue";
import MaterialAPI, {
  MaterialPageVO,
  MaterialForm,
  MaterialPageQuery,
  Material_LABEL,
  MaterialType,
} from "@/api/business/material/material.api";
import { cloneDeep } from "lodash-es";

defineOptions({
  name: "Material",
  inheritAttrs: false,
});

const queryFormRef = ref();
const roleFormRef = ref();
const categoryTreeRef = ref();
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
// 分类下拉数据源
const categoryOptions = ref<OptionType[]>();
let keepFileIds: number[] = [];

const queryParams = reactive<MaterialPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 客户表格数据
const houseList = ref<MaterialPageVO[]>();

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 客户表单
const defaultFormData = {
  id: "",
  name: "",
  type: MaterialType.MAIN,
  code: "",
  spec: "",
  unit: "",
  remark: "",
  price: 1,
  costPrice: 1,
  files: [],
  keepIds: [],
  attachments: [],
};
const formData = reactive<MaterialForm>(cloneDeep(defaultFormData));

const rules = reactive({
  name: [{ required: true, message: "请输入材料名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入市场价格", trigger: "blur" }],
  costPrice: [{ required: true, message: "请输入成本价格", trigger: "blur" }],
  type: [{ required: true, message: "请选择材料类型", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择定额分类", trigger: "blur" }],
});

// 获取数据
function fetchData() {
  loading.value = true;
  MaterialAPI.getPage(queryParams)
    .then((data) => {
      houseList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 打开材料信息弹窗
async function handleOpenDialog(roleId?: string) {
  // 加载分类下拉数据源
  categoryOptions.value = categoryTreeRef.value.deptList;
  if (roleId) {
    dialog.title = "修改材料信息";
    await MaterialAPI.getFormData(roleId)
      .then((data) => {
        Object.assign(formData, data, {
          price: parseFloat((data.price as string) || "1"),
          costPrice: parseFloat((data.costPrice as string) || "1"),
        });
        if (!data.attachments) {
          data.attachments = [];
        }

        data.attachments.forEach(({ id, name, previewUrl }) => {
          formData.files?.push({
            uid: id ? Number(id) : undefined,
            name: name ?? "",
            url: previewUrl,
            status: "success",
          });
          keepFileIds.push(Number(id));
        });
      })
      .finally(() => {
        dialog.visible = true;
      });
  } else {
    dialog.visible = true;
    dialog.title = "新增材料信息";
  }
}

// 提交材料信息表单
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (formData.id) {
        const keepIds: number[] = AttachUtil.getKeepIds(keepFileIds, formData.files);
        formData.keepIds = keepIds;
        MaterialAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        MaterialAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  Object.assign(formData, cloneDeep(defaultFormData));
  keepFileIds = [];
}

// 删除
function handleDelete(roleId?: string) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    MaterialAPI.deleteById(roleIds)
      .then(() => {
        ElMessage.success("删除成功");
        handleResetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

onMounted(() => {
  handleQuery();
});
</script>
